package com.oa.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;

import com.oa.dao.DeptDao;
import com.oa.entity.Dept;

public class DeptDaoImpl implements DeptDao {
	//不会在项目中两个
	private JdbcTemplate jdbcTemplate;
	private NamedParameterJdbcTemplate npjt;

	@Override
	public Integer saveDept(Dept dept) {
		String sql="insert into dept(dname,loc)values(?,?)";
		int result = jdbcTemplate.update(sql, dept.getDname(),dept.getLoc());
		return result;
	}

	@Override
	public Integer deleteDept(Integer id) {
		String sql="delete from dept where deptno=?";
		int result  = jdbcTemplate.update(sql, id);
		return result;
	}
	public int deleteDept(int deptno) {
		String sql="delete from dept where deptno=:deptno";
		SqlParameterSource  paramSource = new MapSqlParameterSource ("deptno",deptno);
		int count = npjt.update(sql, paramSource);
		return count;
	}
	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	public Dept findById(Integer id) {
		String sql="select * from dept where deptno=?";
	    Dept dept = 	 jdbcTemplate.queryForObject(sql, new Object[]{id}, new DeptMapper() );
		return dept;
	}
	private static final class DeptMapper implements RowMapper<Dept>{

		@Override
		public Dept mapRow(ResultSet rs, int rowNum) throws SQLException {
			Dept dept  =new Dept();
			dept.setDeptno(rs.getInt("deptNo"));
			dept.setDname(rs.getString("dname"));
			dept.setLoc(rs.getString("loc"));
			return dept;
		}
		
	}
	@Override
	public List<Dept> findAll() {
		String sql="select * from dept";
		List<Dept> list = jdbcTemplate.query(sql, new DeptMapper());
		return list;
	}

	public NamedParameterJdbcTemplate getNpjt() {
		return npjt;
	}

	public void setNpjt(NamedParameterJdbcTemplate npjt) {
		this.npjt = npjt;
	}

	

	

}
